package assignment;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2025-02-19
 * Time: 21:35
 */
public class Demo6 {
    // 创建一个共享的锁对象
    private final static Object lock = new Object();
    // 当前线程的执行顺序
    private static int currentThread = 3;

    public static void main(String[] args) {
        // 创建三个线程
        Thread threadA = new Thread(() -> printThread("a", 1));
        Thread threadB = new Thread(() -> printThread("b", 2));
        Thread threadC = new Thread(() -> printThread("c", 3));

        // 启动线程
        threadA.start();
        threadB.start();
        threadC.start();
    }

    // 定义线程执行的方法
    private static void printThread(String name, int order) {
        synchronized (lock) {
            // 循环等待，直到轮到当前线程执行
            while (currentThread != order) {
                try {
                    lock.wait(); // 等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 打印线程名称
            System.out.println(name);
            // 更新当前线程顺序
            currentThread--;
            // 唤醒其他线程
            lock.notifyAll();
        }
    }
}
